/**
 * urlname 例：url链接
 * time 为时间 xx/秒		默认30秒
 * count 为次数			默认 30秒/15次
 */
 import vconf from '../utils/vconf.js'
 const config = vconf('config.yml')
 const { apitimecount } = config

 const apiLimit = {}

 export default function(fastify, urlname, time, count) {
   //false为关闭redis限流
   if (!apitimecount.open) return Promise.resolve(true)

   const api_limit =  apiLimit[`limit_${urlname}`] || []
 
   let [
      api_time = 0, //获取 访问API时间间隔
      api_count = 0, //获取 访问API次数间隔的时间
   ] = api_limit 
 
   let datetime = new Date().getTime()

   if (api_time && api_count) {
     //Api时间限制
     let second = (datetime - parseInt(api_time)) / 1000
 
     if (second < time) {
       //Api次数限制
       let add = parseInt(api_count) + 1
       if (add > count) return Promise.resolve(false)
       api_limit[1] = add
     } else {
      api_limit[0] = datetime
      api_limit[1] = 1
     }
   } else {
    api_limit[0] = datetime
    api_limit[1] = 1
   }
   apiLimit[`limit_${urlname}`] = api_limit
   
   return Promise.resolve(true)
 }
 